package com.woyao;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.woyao.core.model.BaseResponse;
import com.woyao.core.model.GetMyReferResponse;
import com.woyao.core.model.ReferSummary;
import com.woyao.core.service.AccountService;
import com.woyao.core.service.ChanceService;
import com.woyao.core.util.Common;
import com.woyao.core.util.ServiceFactory;

import java.io.IOException;
import java.util.List;

import retrofit2.Call;

import static com.woyao.WoyaoooApplication.userId;

public class ReferActivity extends AppCompatActivity {
    ProgressDialog progressDialog;

    private  Integer demand_id ;
    private  String demand_title ;

    private ReferAdapter referAdapter;
    private RecyclerView referList = null;
    LinearLayoutManager referLayoutManager = null;

    private SearchView mSearchView;
    private TextView  demandTitle;
    private TextView  relationCount;


    private ContentResolver cr;

    private Button sendContactbook;
    private Button sendWechat;
    private Button sendMatch;

    private String from = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_refer);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        ab.setDisplayShowHomeEnabled(true); // show or hide the default home button
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setDisplayShowCustomEnabled(true); // enable overriding the default toolbar layout

        referLayoutManager = new LinearLayoutManager(this);
        referLayoutManager.setOrientation(OrientationHelper.VERTICAL);
        referList = (RecyclerView)findViewById(R.id.refer);
        referList.setLayoutManager(referLayoutManager);
        referList.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));

        Intent intent = getIntent();
        demand_id =  intent.getIntExtra("id",8247);
        demand_title =  intent.getStringExtra("title");

        from = intent.getStringExtra("from");

        if  (from != null && from.equals("register")) {
            this.setTitle("4/4. 介绍合作 ");
        }else{
            this.setTitle("介绍合作");
        }

        demandTitle  = (TextView) findViewById(R.id.demandtitle_refer);

        demandTitle.setText(  demand_title  );

        relationCount  = (TextView) findViewById(R.id.myrelation_count);



        mSearchView = (SearchView) findViewById(R.id.refer_search);
//        mSearchView.setVisibility(View.GONE);
        mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                loadCandidates(query);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });



        Button nextbtn = (Button) findViewById(R.id.refer_done);

        nextbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (from != null && from.equals("register")) {
                    Intent intent = new Intent();
                    intent.putExtra("from", from );
                    intent.setClass(ReferActivity.this,ChanceActivity.class);
                    startActivity( intent);
                }else{
                    finish();
                }

            }
        });


        sendContactbook = (Button)  findViewById(R.id.sendmobile);

        sendContactbook.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(ReferActivity.this, "功能正在开发!", Toast.LENGTH_SHORT).show();
//                tryGetContacts(ReferActivity.this);
            }
        });

        sendWechat = (Button)  findViewById(R.id.sendwechat);

        sendWechat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(ReferActivity.this, "功能正在开发!", Toast.LENGTH_SHORT).show();
            }
        });

        sendMatch = (Button)  findViewById(R.id.sendrefer);

        sendMatch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                refer( );
            }
        });

        loadCandidates("recommend");


    }

    public  void tryGetContacts(Activity context) {

        if (ContextCompat.checkSelfPermission(context,android.Manifest.permission.READ_CONTACTS)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions( context,
                    new String[]{android.Manifest.permission.READ_CONTACTS},
                    1);
        }else {
            getContacts();
        }

    }

    private void getContacts() {
        try {
            progressDialog = new ProgressDialog(this);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.setMessage("正在加载通讯录······");
            progressDialog.show();

            cr = getContentResolver();
            Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
            Cursor cs = null;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
                cs = cr.query(uri, null, null, null, null, null);
                StringBuilder sb = new StringBuilder();
                while (cs.moveToNext()) {
                    //拿到联系人id 跟name
                    int id = cs.getInt(cs.getColumnIndex("_id"));
                    String name = cs.getString(cs.getColumnIndex("display_name"));
                    //得到这个id的所有数据（data表）
                    Uri uri1 = Uri.parse("content://com.android.contacts/raw_contacts/" + id + "/data");
                    Cursor cs2 = cr.query(uri1, null, null, null, null, null);
                    sb.append("displayname:" + name + ";");
                    while (cs2.moveToNext()) {
                        //得到data这一列 ，包括很多字段
                        String data1 = cs2.getString(cs2.getColumnIndex("data1"));
                        //得到data中的类型
                        String type = cs2.getString(cs2.getColumnIndex("mimetype"));
                        String str = type.substring(type.indexOf("/") + 1, type.length());//截取得到最后的类型
//                        if ("name".equals(str)) {//匹配是否为联系人名字
//                            sb.append("name:" + data1 + ";");
//                        }
//                        if ("phone_v2".equals(str)) {//匹配是否为电话
//                            sb.append("phone:" + data1 + ";");
//                        }
                        if ( str!=null &&  data1 != null ) {
                            sb.append(str + ":" + data1.replace(':', ' ').replace(';', ' ').replace('#', ' ') + ";");
                        }
                        Log.i("test", data1 + "       " + type);
                    }
                    sb.append("#");
                }
                final String content = sb.toString();

                AsyncTask<Void, Void, Boolean> task = new AsyncTask<Void, Void, Boolean>() {
                    @Override
                    protected Boolean doInBackground(Void... params) {
                        AccountService svc = ServiceFactory.get(AccountService.class);
                        Call<BaseResponse> responseCall = svc.setProfileAttr(WoyaoooApplication.userId,"contacts",content);
                        Boolean ret = true ;
                        try {
                            BaseResponse response = responseCall.execute().body();
                            ret= response.isSuccess();
                        } catch (IOException e) {
                            e.printStackTrace();
                            ret = false;
                        }
                        return ret;
                    }

                    @Override
                    protected void onPostExecute(final Boolean success) {
                        progressDialog.dismiss();
                        if (success) {
                            Toast.makeText(ReferActivity.this, "已经导入通讯录", Toast.LENGTH_LONG).show();
                            loadCandidates("contactbook");
                        } else {
                            Common.showSnack( ReferActivity.this, sendContactbook, "没有成功导入，请稍候重试");
                        }
                    }

                    @Override
                    protected void onCancelled() {
                        progressDialog.dismiss();
                    }
                };
                task.execute((Void) null);
            }


        }catch (Exception e){
            Toast.makeText(this,"不能访问通讯录", Toast.LENGTH_SHORT).show();
        }

    }



    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1: {    // 1 for location
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    getContacts();
                } else {
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                }
                return;
            }
            // other 'case' lines to check for other
            // permissions this app might request
        }
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        finish();
        return true;
    }

    private void loadCandidates( final  String keyword) {
        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("拼命加载中······");
        progressDialog.show();


        AsyncTask<Void, Void, GetMyReferResponse> task = new AsyncTask<Void, Void, GetMyReferResponse>() {
            @Override
            protected GetMyReferResponse doInBackground(Void... params) {
                ChanceService svc = ServiceFactory.get(ChanceService.class);
                Call<GetMyReferResponse> responseCall = svc.getMyRefer(userId,demand_id,keyword);
                try {
                    GetMyReferResponse r = responseCall.execute().body();
                    return r;
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                }

            }

            @Override
            protected void onPostExecute(final GetMyReferResponse response) {
                progressDialog.dismiss();
                if (response != null ) {
                    renderThem(response.getContent() );
                } else {
                    Common.showSnack(ReferActivity.this,referList,"网络错误，请重试");
                }
            }

            @Override
            protected void onCancelled() {

            }
        };
        task.execute((Void) null);

    }


    private  void renderThem(List<ReferSummary> refers){

        referAdapter = new ReferAdapter(this,  refers );

        if (refers.size() >0) {
            relationCount.setText("我有" + refers.size() + "个合作");
        }else{
            relationCount.setText("我没有沟通中的合作");
        }

        referList.setAdapter(referAdapter);
    }


    private void refer( ) {
        final String toids = referAdapter.getSelection();

        if ( toids.equals("") ) {
            finish();
            return;
        }

        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("发送消息······");
        progressDialog.show();

        AsyncTask<Void, Void, BaseResponse> task = new AsyncTask<Void, Void, BaseResponse>() {
            @Override
            protected BaseResponse doInBackground(Void... params) {
                ChanceService svc = ServiceFactory.get(ChanceService.class);
                Call<BaseResponse> responseCall = svc.refer(userId,  demand_id,"",toids);
                try {
                    BaseResponse r = responseCall.execute().body();
                    return r;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(final BaseResponse ret) {
                progressDialog.dismiss();

                if (ret != null) {
                    if (ret.isSuccess()) {
                        Toast.makeText(ReferActivity.this, "发送成功!", Toast.LENGTH_SHORT).show();

                    }else{
                        Toast.makeText(ReferActivity.this, "发送失败了!", Toast.LENGTH_SHORT).show();
                    }
                }

            }

            @Override
            protected void onCancelled() {

            }
        };
        task.execute((Void) null);
    }


//    private void finishRefer(){
//
//        Dialog alertDialog = new AlertDialog.Builder(ReferActivity.this).
//                setTitle("信息").
//                setMessage("完成介绍").
//                setIcon(R.drawable.ic_launcher).
//                setPositiveButton("确定", new DialogInterface.OnClickListener() {
//
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//
//                    }
//                }).
//                create();
//        alertDialog.show();
////        Common.alert(ReferActivity.this, "完成介绍");
////        finish();
//    }

}
